package cn.edu.nju.freshdelivery.util;
import java.lang.reflect.Field; 
import java.lang.reflect.Type; 
import java.net.URI;
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 
/**

.
* 解析JSON类
* 核心使用几个方法
* 获取字符串String getString(String key) ;参数为字符串名
* 获取对象Object getObject(Class<?> c);参数为对象的类，如User.class，默认键为类的小写，如user
* 获取列表List<Object> getList(String key ,Class<?> c);参数为List的名称以及List中对象的类
*调用时处理异常，为服务器返回的数据异常
*/ 
public class JsonUtil { 
    private static final String TAG = "jsonUtil"; 
    private JSONObject jsonObject; 
//	public static String rootUrl = "http://192.168.0.100:8080/FreshDelivery/";
	private static final String rootUrl = "http://10.0.2.2:8080/FreshDelivery/";
	public static String getRootURL() {
		return rootUrl;
	}

/***********Constructors************/
    private JsonUtil(String json) 
    { 
        Log.e(TAG, "json="+json); 
        jsonObject = getJsonObject(json); 
        if(jsonObject==null) 
        { 
            Log.e(TAG, "jsonobject is null"); 
        } 
    } 
     
    public JsonUtil() { 
        super(); 
    } 

    public static JsonUtil newJsonUtil(String json) 
    { 
        JsonUtil util =  new JsonUtil(json); 
        return util; 
    } 
    
    
	/**
	 * 这里采用post请求方式，使用一个List保存请求参数，在外部写为： 
	 // List <NameValuePair> params = new ArrayList <NameValuePair>(); 
	 // params.add(new BasicNameValuePair("user","123")); 
	 // params.add(new BasicNameValuePair("pass", "3421"));
	 * 然后把这个List作为参数调用此方法
	 * 
	 * @param tailURL
	 *            请求的url结尾，比如userAddAction
	 * @return
	 */
	public static String getOut(String tailURL, List<NameValuePair> params) {
		String out = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost httpRequest = new HttpPost(new URI(rootUrl + tailURL));
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse response = client.execute(httpRequest);
			System.out.println(response.getStatusLine());
			if (response.getStatusLine().getStatusCode() != 200) { // 200为成功
				System.out
						.println("response.getStatusLine().getStatusCode() != 200");
				return null;
			}

			HttpEntity entity = response.getEntity();
			System.out.println(entity==null);
			if (entity != null) {
				System.out.println("entity!=null");
				out = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return out;
	}
	

    /**
     * get json object 
     * @param json  json data
     * @return  JOSNObject
     */ 
    public JSONObject getJsonObject(String json)  
    { 
        JSONObject jsonObject = null; 
        try { 
            jsonObject = new JSONObject(json); 
        } catch (JSONException e) { 
            Log.e(TAG, "create jsonobject exception"); 
            e.printStackTrace(); 
        } 
        return jsonObject; 
    } 
    /**
     * get String data
     * @param json  json data
     * @param key param
     * @return  String data
     * @throws JSONException
     */ 
    public  String getString(String key) throws JSONException 
    { 
        if(jsonObject!= null) 
        { 
            return jsonObject.getString(key); 
        }else{ 
            return null; 
        } 
         
    } 
    /**
     * get String data
     * @param json  json data
     * @param key param
     * @return  int data
     * @throws JSONException
     */ 
    public  int getInt(String key) throws JSONException 
    { 
        if(jsonObject!= null) 
        { 
            return jsonObject.getInt(key); 
        }else{ 
            return -1; 
        } 
         
    } 
    /**
     * get Double data
     * @param json  json data
     * @param key param
     * @return  double data
     * @throws JSONException
     */ 
    public  double getDouble(String key) throws JSONException 
    { 
        if(jsonObject!= null) 
        { 
            return jsonObject.getDouble(key); 
        }else{ 
            return -1; 
        } 
         
    } 
    /**
     * This Method use in jsonObject get current class with object 
     * @param jsonObject
     * @param c  class 
     * @return  object 
     * @throws Exception
     */ 
    public  Object getObject(Class<?> c) throws Exception 
    { 
        if(jsonObject!=null) 
        { 
            return getObject(c.getSimpleName().toLowerCase(),c); 
        }else{ 
            return null; 
        } 
    } 
    /**
     * This Method use in jsonObject get current class with object 
     * @param jsonObject
     * @param key   query key 
     * @param c  class 
     * @return  object 
     * @throws Exception
     */ 
    public  Object getObject(String key,Class<?> c) throws Exception 
    { 
        if(jsonObject!=null) 
        { 
            return getObject(jsonObject, key, c); 
        }else{ 
            return null; 
        } 
    } 
    public Object getObject(JSONObject jsonObject,Class<?> c) throws Exception 
    { 
        return getObject(jsonObject, c.getSimpleName().toLowerCase(), c); 
    } 
    /**
     * This Method use in jsonObject get current class with object 
     * @param jsonObject
     * @param key   query key 
     * @param c  class 
     * @return  object 
     * @throws Exception
     */ 
    public  Object getObject(JSONObject jsonObject, String key,Class<?> c) throws Exception 
    { 
        Log.w(TAG,"key ==  " + key); 
        Object bean =null ; 
         
        if(jsonObject!=null) 
        { 
            JSONObject jo = null; 
            if(key!=null) 
            { 
                 jo =  jsonObject.getJSONObject(key); 
            }else{ 
                jo = jsonObject; 
            } 
            if(jo!=null) 
            { 
                if(c.equals(null)) 
                { 
                    Log.e(TAG, "class is null"); 
                    bean = jo.get(key); 
                }else{ 
                	//新建object实例
                    bean = c.newInstance();
                    //获取object的域
                    Field[] fs = c.getDeclaredFields(); 
                    for (int i = 0; i < fs.length; i++) { 
                        Field f = fs[i]; 
                        f.setAccessible(true); 
                        Type type = f.getGenericType();
                        //从jsonObject中获取对象的某域的值
                        String value = jo.getString(f.getName()); 
                        Log.e(TAG,f.getName()+"="+value); 
                        
                        //设置对象域的值
                        if(type.equals(int.class)) 
                        { 
                            f.setInt(bean,Integer.valueOf(value)); 
                        }else if(type.equals(double.class)){ 
                            f.setDouble(bean, Double.valueOf(value)); 
                        }else{ 
                            f.set(bean,value); 
                        } 
                    } 
                } 
            }else{ 
                Log.e(TAG, "in jsonobject not key "); 
            } 
        }else{ 
            Log.e(TAG, "current param jsonobject is null"); 
        } 
        return bean; 
    } 
    /**
     * This method use in jsonObject get list object
     * @param key  list key
     * @param objectKey  object key
     * @param c  object
     * @return   list
     * @throws Exception
     */ 
    public List<Object> getList(String key ,Class<?> c) throws Exception 
    { 
        List<Object> list = null; 
        if(jsonObject!=null) 
        { 
            JSONArray jsonArray = jsonObject.getJSONArray(key); 
            if(!jsonArray.isNull(0)) 
            { 
                list = new ArrayList<Object>(); 
                for (int i = 0; i < jsonArray.length(); i++) { 
                    JSONObject jsObject = jsonArray.getJSONObject(i); 
                    Object object = getObject(jsObject, null, c); 
                    list.add(object); 
                } 
            } 
        } 
        return list; 
    } 
    /**
     * Test class field value  
     * @param c  
     * @param classObject
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */ 
    public static String getFieldValue(Class<?> c,Object classObject) throws IllegalArgumentException, IllegalAccessException 
    { 
        StringBuffer sb = new StringBuffer(); 
        Field[] fs = c.getFields(); 
        for (int i = 0; i < fs.length; i++) { 
            String s = fs[i].getName()+"="+fs[i].get(classObject); 
            sb.append(s).append("\n"); 
        } 
//      Log.e(TAG, sb.toString()); 
        return sb.toString(); 
    } 
}
